<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>

  <script>
    const arr = [
      { id: 1, parentId: null, name: "Root" },
      { id: 2, parentId: 1, name: "Child 1" },
      { id: 3, parentId: 1, name: "Child 2" },
      { id: 4, parentId: 2, name: "Grandchild 1" },
    ]

    function treeToArray(arr, parentId = null) {
      let result = []
      let map = new Map()
      arr.forEach((item) => {
        map.set(item.id, { ...item, children: [] })
      })

      arr.forEach((item) => {
        const parent = map.get(item.parentId)
        if (parent) {
          parent.children.push(map.get(item.id))
        } else {
          result.push(map.get(item.id))
        }
      })

      return result
    }

    console.log(treeToArray(arr))
  </script>
</html>
